//
//  EWImagePickerKit.m
//  TestImagePicker
//
//  Created by hemingway payegis on 13-5-14.
//  Copyright (c) 2013年 payegis. All rights reserved.
//

#import "RYCImagePickerKit.h"

@interface RYCImagePickerKit ()
@property (nonatomic ,retain) UIViewController* fromViewController;
@end

@implementation RYCImagePickerKit

+ (RYCImagePickerKit*)sharedInstance
{
    static RYCImagePickerKit* sImagePickerKit = nil;
    if (!sImagePickerKit)
    {
		@synchronized(self)
        {
			if (!sImagePickerKit)
            {
                sImagePickerKit = [[self alloc] init];
			}
		}
	}
	return sImagePickerKit;
}

- (void)dealloc
{
    self.fromViewController = nil;
    self.completionBlock = nil;
    [super dealloc];
}

- (void)showImagePickerFromViewController:(UIViewController*)viewController
{
    _fromViewController = viewController;
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
    [actionSheet showFromRect:viewController.view.bounds inView:viewController.view animated:YES];
    [actionSheet release];
}

- (void)showImagePickerFromViewController:(UIViewController*)viewController sourceType:(UIImagePickerControllerSourceType)sourceType
{
    _fromViewController = viewController;
    
    UIImagePickerController* picker = [[UIImagePickerController alloc] init];
    picker.sourceType = sourceType;
    picker.allowsEditing = YES;
    picker.delegate = self;
    [viewController presentViewController:picker animated:YES completion:nil];
    [picker release];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (0 == buttonIndex)
    {
        [self showImagePickerFromViewController:_fromViewController sourceType:UIImagePickerControllerSourceTypeCamera];
    }
    else if (1 == buttonIndex)
    {
        [self showImagePickerFromViewController:_fromViewController sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage* orginalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (orginalImage)
    {
        if (_completionBlock)
        {
            _completionBlock(orginalImage);
        }
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}
@end
